/* 

		SVN 
		$LastChangedRevision: 13 $
		$LastChangedDate: 2014-08-07 21:24:10 +0000 (Thu, 07 Aug 2014) $
		$LastChangedBy: picciux@gmail.com $
		 
*/

/******************************* GLOBS *********************************/
var ImGallery = {
	feedType: {
		PICASA: 1,
		RSS: 2
	},
		
	prefs: {
		FEED_TYPE: "feedType",
		USER_ID: "userid",
		SLIDESHOW: "slideshow",
		SLIDE_INTERVAL: "ssinterval",
		SHOW_CAPTION: "showCaption",
		AUTO_HEIGHT: "autoHeight"
	},
	
	picasa: {
		prefs: {
			ALBUM_ID: "picasaAlbumId",
			AUTH_KEY: "picasaAuthKey"			
		},
		
		BASE_URL: "https://picasaweb.google.com/data/feed/api/user/",
		
		listAlbumsURL: function(userid, authkey) {
			if (authkey != null && authkey.length > 0)
				authkey = "&authkey=" + authkey;
			else
				authkey = "";
			
			return ImGallery.picasa.BASE_URL + 
				encodeURIComponent(userid) + 
				"?fields=" + 
				encodeURIComponent(
						"entry(title,link,gphoto:id,gphoto:access,media:*)"
				) + authkey;			
		},
		
		viewAlbumURL: function(userid, albumid, authkey) {
			if (authkey != null && authkey.length > 0)
				authkey = "&authkey=" + authkey;
			else
				authkey = "";
			
			return ImGallery.picasa.BASE_URL + 
				encodeURIComponent(userid) + "/albumid/" + albumid +
				"?fields=" + 
				encodeURIComponent(
						"entry(id,content,title,summary,media:*)"
				) + authkey;				
		}
	},
	
	rss: {
		prefs: {
			URL: "rssFeedURL"
		}
	}
};

//TODO to remove after debug
function dump_ob(obj, indent, te) {
	if (indent > 10) return "STOP";
	
	var tab_t = "&nbsp;&nbsp;&nbsp;";
	
	var tab = "";
	for (var n = 0; n < indent; n++) tab += tab_t;

	te.innerHTML += tab;
	if (typeof(obj) == "object") te.innerHTML += "{<br />";
	
	var p;
	for (var i in obj) {
		if (i == "data") continue;
		p = obj[i];
		te.innerHTML += tab + tab_t + i + ": ";
		if (typeof(p) == "object")
			dump_ob(p, indent + 1, te);
		else 
			te.innerHTML += p + "<br />";
	}

	if (typeof(obj) == "object") te.innerHTML += tab + "}<br />";
}

function dump(obj, target) {
	var t = document.getElementById(target);
	dump_ob(obj, 0, t);
	t.style.display = "block";
}

function getTextNode(node) {
	if (node.childNodes[0])
		return node.childNodes[0].nodeValue;
	else
		return "";
}
/******************************* GLOBS *********************************/

var gPrefs = new gadgets.Prefs();

var feedType = gPrefs.getInt(ImGallery.prefs.FEED_TYPE);

var feedURL;

switch (feedType) {
case ImGallery.feedType.PICASA:
	feedURL = ImGallery.picasa.viewAlbumURL(
			gPrefs.getString(ImGallery.prefs.USER_ID), 
			gPrefs.getString(ImGallery.picasa.prefs.ALBUM_ID), 
			gPrefs.getString(ImGallery.picasa.prefs.AUTH_KEY)
	);
	break;
	
case ImGallery.feedType.RSS:
	feedURL = gPrefs.getString(ImGallery.rss.prefs.URL);										
	break;
}

var showCaption = gPrefs.getBool(ImGallery.prefs.SHOW_CAPTION);
var slideshow = gPrefs.getBool(ImGallery.prefs.SLIDESHOW);
var ssinterval = gPrefs.getInt(ImGallery.prefs.SLIDE_INTERVAL);
var ssindex = 0;
var timeoutRef;

var images = new Array();

function ThumbData(url, width, height) {
	this.url = url;
	this.width = width;
	this.height = height;
}

function ImageData(title,url,width,height,thumbnails) {
	this.title = title;
	this.url = url;
	this.width = width;
	this.height = height;
	this.thumbnails = thumbnails;
}

function imageLinkId(i) {
	return "imageLink_" + i; 
}

function setImage(n) {
	try {

		if (timeoutRef) clearTimeout(timeoutRef);

		document.getElementById('largeImage').src = images[n].url;
	
		if (showCaption) {
			document.getElementById("caption").innerHTML = images[n].title;
		}
	
		for (var i = 0; i < images.length; i++) {
			if (i != n)
				document.getElementById(imageLinkId(i)).className = '';
			else
				document.getElementById(imageLinkId(i)).className = 'active';
		}


		if (slideshow) {
			timeoutRef = setTimeout(
				function() {
					if (ssindex > images.length -1) ssindex = 0;
					setImage(ssindex++);
				},
				ssinterval * 1000
			);
		}

	} catch (err) {
		alert("setImage: " + err.message);
	}					
}

function addImage(i) {
	try {
		var img = images[i];
		var list_item = document.createElement("li");
		var link = document.createElement("a");
		link.id = imageLinkId(i);
		link.href=img.url;
		link.title=img.title;
		link.onclick = function() { 
			setImage(i);
			ssindex = i+1; 
			return false; 
		};
	
		var th = document.createElement("img");
		th.src = img.thumbnails[0].url;
		link.appendChild(th);
		list_item.appendChild(link);
		document.getElementById("imglist").appendChild(list_item);
	} catch (err) {
		alert("addImage: " + err.message);
	}
}

function parseMediaGroup(x) {
	var title = "", url = "", width = 0, height = 0;
	var thumbs = new Array();
	var tc = 0;
	
	try {
		for (var i = 0; i < x.childNodes.length; i++) {
			var n = x.childNodes[i];
			
			if (n.nodeName == "media:title") {
				title = getTextNode(n);
			} else if (n.nodeName == "media:content") {
				if (n.getAttribute("medium") != "image") continue;
				url = n.getAttribute("url");
				width = parseInt(n.getAttribute("width"));
				height = parseInt(n.getAttribute("height"));
			} else if (n.nodeName == "media:thumbnail") {
				thumbs[tc++] = new ThumbData(
						n.getAttribute("url"),
						parseInt(n.getAttribute("width")),
						parseInt(n.getAttribute("height"))
				);
			}
		}
	} catch (err) {
		alert("parseMediaGroup: " + err.message);
	}					
	
	return new ImageData(title, url, width, height, thumbs);
}

function parseEntry(item) {
	var title = null;
	var summary = null;
	var ret = null;
	
	for (var x = 0; x < item.childNodes.length; x++) {
		if (item.childNodes[x].nodeName == "media:group")
			ret = parseMediaGroup(item.childNodes[x]);
		if (item.childNodes[x].nodeName == "title")
			title = getTextNode(item.childNodes[x]);
		if (item.childNodes[x].nodeName == "summary")
			summary = getTextNode(item.childNodes[x]);
	}
	
	if (ret != null) {
		if (summary != null && summary != "")
			ret.title = summary;
		else if (title != null && title != "")
			ret.title = title;
	}
	
	return ret;
}

function parseFeed(obj) {
	var ic = 0;

	var maxWidth = 0;
	var maxHeight = 0;
	var maxWidthOfMaxHeight;
	var autoHeight = gPrefs.getBool(ImGallery.prefs.AUTO_HEIGHT);
	var padW = 10;
	var padH = 10;
	var thumbsH = 60;
	var scrollbarH = 17;

	var captionH = 0;

	if (showCaption) {
		captionH = 15 + 5 + 15; //height + top pad + bottom pad
	}

	try {
		var root = null;
	
		switch(feedType) {
		case 1: //Picasa
			root = obj.data.getElementsByTagName("feed").item(0);
			break;
		
		case 2: //RSS
			root = obj.data.getElementsByTagName("channel").item(0);						
			break;
		}
		
		for (var i = 0; i < root.childNodes.length; i++) {
			if (
					root.childNodes[i].nodeName == "item" || 
					root.childNodes[i].nodeName == "entry") {
				var im = parseEntry(root.childNodes[i]);
				if (im.width > maxWidth) maxWidth = im.width;
				if (im.height > maxHeight) {
					maxHeight = im.height;
					maxWidthOfMaxHeight = im.width;									
				}
				images[ic] = im;
				ic++;
			}
		}

		var dims = gadgets.window.getViewportDimensions();
		
		var large = document.getElementById("large");
		
		//calculating max size for large container
		var aWidth = large.parentNode.clientWidth;
		var aHeight = dims.height - thumbsH - padH - captionH - scrollbarH;

		maxWidth = aWidth - padW;
		if (aWidth < maxWidthOfMaxHeight + padW)
			maxHeight = ( maxHeight * ((aWidth - padW) / maxWidthOfMaxHeight)); 	

		if ((! autoHeight)) {
			maxHeight = aHeight - padH;
		}
		
		large.style.width = (maxWidth + padW) + "px";
		large.style.maxWidth = (maxWidth + padW) + "px";
		large.style.height = (maxHeight + padH) + "px";
		large.style.maxHeight = (maxHeight + padH) + "px";
		
		var largeImg = document.getElementById("largeImage");
		largeImg.style.maxWidth = maxWidth + "px";
		largeImg.style.maxHeight = maxHeight + "px";
		
		var caption = document.getElementById("caption");
		
		if (showCaption) {
			caption.style.width = maxWidth + "px";
			caption.style.maxWidth = maxWidth + "px";
			caption.style.display = "block";
		}
		
		document.getElementById("thumbs").style.width = (maxWidth + padW) + "px";
		
		for (var i = 0; i < ic; i++) addImage(i);
		
		if (autoHeight) gadgets.window.adjustHeight();

		if ( images.length > 0 ) setImage(0);


	} catch(err) {
		alert("parseFunc: " + err.message);
	}
}

function doInit() {
	/*document.getElementById("caption").style.color = 
		gadgets.skins.getProperty(gadgets.skins.Property.FONT_COLOR);*/
	
	var params = {};

	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
	gadgets.io.makeRequest(feedURL, parseFeed, params);

	ssindex = 1;
}

gadgets.util.registerOnLoadHandler(doInit);
